<template>
  <div>
    <el-upload
      list-type="picture-card"
      :limit="1"
      action="#"
      :file-list="fileList"
      :class="{disabled:fileList.length>=1}"
      :on-remove="onRemove"
      :on-change="onChange"
      :on-preview="onPreview"
      :before-upload="beforeUpload"
      :http-request="upload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress
      v-if="isShowPercent"
      :percentage="percentage"
      :show-text="false"
      style="width: 146px"
    />
    <el-dialog title="预览" :visible="isShowDialog" @close="isShowDialog =false">
      <el-row type="flex" justify="center">
        <img :src="previewSrc" alt="">
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDITSDk2GI5f3C9uTo7C2f4FCCyWpulNnz',
  SecretKey: '0lHYaR2OWQ4SbVP7brthIgogIfmeGciY'
})
export default {
  data() {
    return {
      fileList: [
        { url: 'https://img1.baidu.com/it/u=3246628741,3439955235&fm=26&fmt=auto' }
      ],
      isShowDialog: false,
      previewSrc: '',
      percentage: 0,
      isShowPercent: false
    }
  },
  methods: {
    onRemove(file, fileList) {
      this.fileList = fileList
    },
    onChange(file, fileList) {
      this.fileList = fileList
    },
    onPreview(file) {
      // console.log(file)
      this.previewSrc = file.url
      this.isShowDialog = true
    },
    beforeUpload(file) {
      // console.log(file)
      const maxSize = 2 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.warning('不能超过2M')
        return false
      }
      const type = ['image/jpeg', 'image/png']
      if (type.indexOf(file.type) === -1) {
        this.$message.warning('只支持类型为jpeg与png')
        return false
      }
    },
    upload(params) {
      // console.log(params)
      this.isShowPercent = true
      cos.putObject({
        // 储存桶名称
        Bucket: 'hr68-1308177462',
        // 地区代码
        Region: 'ap-guangzhou',
        // 储存的文件名
        Key: Date.now().toString(32) + params.file.name,
        // 标准储存类型(固定)
        StorageClass: 'STANDARD',
        // 文件对象本身
        Body: params.file,
        // 进度发生变化的回调
        onProgress: (progressData) => {
          // console.log(JSON.stringify(progressData))
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        // 上传完毕回调函数
        // console.log(err || data)
        if (!err) {
          this.fileList[0].status = 'success'
          this.fileList[0].url = `http://${data.Location}`
        } else {
          this.$message.error(err)
        }
        setTimeout(() => {
          this.isShowPercent = false
        }, 1000)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.disabled{
  ::v-deep .el-upload--picture-card{
    display: none;
  }
}
</style>
